package nagper.com;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.PowerManager;
import android.view.*;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import android.hardware.Camera;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.ImageButton;

public class Cam extends Activity implements SurfaceHolder.Callback{
	
    SurfaceView sv;
    SurfaceHolder sh;
	Camera myCam;
	FileOutputStream fos;
	Camera.Parameters myCamPar;
	Socket s;
	DataOutputStream dos;
	ImageButton exitButton, connectButton;
    OnClickListener exitButtonListener,connectButtonListener;
    PowerManager.WakeLock wl;
    Camera.AutoFocusCallback afc;
	boolean connected = false;
	Camera.PreviewCallback cpc;
	SharedPreferences sp;
	byte[] rgbdata = new byte[176*144*3];
	byte[] datacopy = new byte[38016];
	
    
    @Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    //Wakelock setup
	    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
	    wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Tag");
		wl.acquire();
		
		//Fullscreen
	    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN );
		requestWindowFeature(Window.FEATURE_NO_TITLE);
	    setContentView(R.layout.main);
	    
	    //Initscreen
	    try {initCam();} catch (FileNotFoundException e) {e.printStackTrace();			}
	    initSurfaceView();
	    
	    //ConnectButton
	    connectButtonListener = new OnClickListener(){
	    	public void onClick(View v){
	    		if (!connected)
	    			startCam();
	    		else stopCam();
	    	}
	    };
	    connectButton = (ImageButton) findViewById(R.id.ImageButton01);
	    connectButton.setOnClickListener(connectButtonListener);
	    
	    //ExitButton
	    exitButtonListener = new OnClickListener(){
	    	public void onClick(View v){
	    		exit();
	    	}
	    };
	    exitButton = (ImageButton) findViewById(R.id.ImageButton02);
	    exitButton.setOnClickListener(exitButtonListener);
	    
	    //SharedPreferences
	    sp = getSharedPreferences(Properties.CAMPREFS, MODE_PRIVATE);
	}
    
	void initCam() throws FileNotFoundException{
        myCam = Camera.open();
        myCamPar = myCam.getParameters();
        myCamPar.setFocusMode(Camera.Parameters.FOCUS_MODE_FIXED);
        myCamPar.setPreviewSize(176,144);
        myCam.setParameters(myCamPar);
            

        cpc = new Camera.PreviewCallback() {			
			@Override
			public void onPreviewFrame(byte[] data, Camera camera) {
				if (connected){
					try {
						dos.write(data,0,data.length);
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		};
        myCam.setPreviewCallback(cpc);
        
        afc = new Camera.AutoFocusCallback(){
        	public void onAutoFocus(boolean success, Camera  camera){
        	}
        };
    }
    
	
    void initSurfaceView(){
		sv = (SurfaceView) findViewById(R.id.SurfaceView01);
        sh = sv.getHolder();
        sh.addCallback(this);
        sh.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);      
        sv.setOnTouchListener(new View.OnTouchListener(){
			@Override
			public boolean onTouch(View v, MotionEvent event) {
	            myCam.autoFocus(afc);
				return true;
			}
        });
    }

    void connect(){
		s = new Socket();
		try {
			s.connect(new InetSocketAddress(sp.getString("ip", "0.0.0.0"), Integer.parseInt(sp.getString("port", "0"))),3000);
			dos = new DataOutputStream(s.getOutputStream());
			connected=true;
			connectButton.setImageResource(R.drawable.disconnectbuttonstates);
		} catch (IOException e) {
			e.printStackTrace();
		}			
	}

	void disconnect(){
		try {
			dos.flush();
			dos.close();
			s.close();
			connected=false;
			connectButton.setImageResource(R.drawable.connectbuttonstates);
		} catch (Exception e) {}
    }
    
    void startCam(){
		connect();
		if (connected)
			myCam.setPreviewCallback(cpc);
	}

	void stopCam(){
    	myCam.setPreviewCallback(null);
    	disconnect();
    }
        
    void exit(){
    	stopCam();
    	wl.release();
		finish();
    }
    
    @Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.menu, menu);
	    return true;
	}

	@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.settings:
        	startActivity(new Intent(this, nagper.com.Properties.class));
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
    
    public void surfaceCreated (SurfaceHolder sfh)
	{
	try{
		myCam.setPreviewDisplay(sfh);
		myCam.startPreview();
	}catch(Exception e){}
	}

	public void surfaceChanged (SurfaceHolder sfh, int format, int width, int height)
    {
    	
    }
    
    public void surfaceDestroyed (SurfaceHolder sfh)
    {
    	myCam.setPreviewCallback(null);
    	myCam.stopPreview();
    	myCam.release();
    }
    
    public void onStop(){
    	super.onStop();
    	disconnect();
    }

    public void onRestart(){
    	super.onRestart();
		myCam=Camera.open();
    }
    
}
